/*
 * @Date: 2022-06-16 19:07:47
 * @Description: style 类型自适应
 */

import { Dimensions, Platform, StyleSheet } from 'react-native'

export { themeColor as color } from './themeColor'

type NamedStyles<T> = StyleSheet.NamedStyles<T>

/** 传入样式自动转rpx */
export function createStyle<T extends NamedStyles<T> | NamedStyles<any>>(styles: T | NamedStyles<T>): T {
  return StyleSheet.create(forStyles(styles)) as T
}

/** 循环样式最外面的 class */
function forStyles(styles: any) {
  for (const key in styles) {
    if (Object.prototype.hasOwnProperty.call(styles, key)) {
      const classStyles = styles[key]
      styles[key] = rpxStyles(classStyles)
      /** 修复部分Android机型上的文字兼容性问题 */
      if ((styles[key].fontSize || styles[key].fontWeight) && Platform.OS === 'android') {
        styles[key].fontFamily = ''
      }
    }
  }
  return styles
}

// app 只有竖屏模式，所以可以只获取一次屏幕尺寸
export const windowSize = Dimensions.get('window')

// UI 默认给图是 750
const uiWidthPx = 750

export function pxToDp(uiElementPx: number) {
  return (uiElementPx * windowSize.width) / uiWidthPx
}

// 字体适配
export const allowFontScaling = Platform.OS === 'ios' ? false : true

// 不自动转rpx的
const filterKeys = ['opacity', 'flex', 'zIndex']

/** 循环样式 */
function rpxStyles(styles: any) {
  for (const key in styles) {
    if (Object.prototype.hasOwnProperty.call(styles, key)) {
      const value = styles[key]
      if (typeof value === 'number') {
        if (filterKeys.indexOf(key) === -1) {
          styles[key] = pxToDp(value)
        }
      }
    }
  }
  return styles
}

export const ZIndex = {
  mask: 50,
  popup: 51,
  effect: 52,
  confirm: 96,
  alert: 97,
  msg: 98,
  feedback: 99,
  loading: 100,
}
